﻿// =====================================================================
// <copyright file="ConfigHelper.cs" author="David R. Guindo">
// 	Copyright (C) 2013. All rights reserved.
// </copyright>
// =====================================================================
// This code is released under the terms of the Apache 2.0 license, 
// http://apache.org/licenses/LICENSE-2.0.html
// =====================================================================

namespace AppBlock.Core
{
    using System;
    using System.Configuration;
    using System.Globalization;

    /// <summary>
    ///     Helper for manage ConfigurationManager configurations.
    /// </summary>
    public static class ConfigHelper
    {
        /// <summary>
        ///     Gets the app setting.
        /// </summary>
        /// <typeparam name="T"> </typeparam>
        /// <param name="name"> The name. </param>
        /// <returns> </returns>
        public static T GetAppSetting<T>(string name)
        {
            if (ConfigurationManager.AppSettings[name] == null)
            {
                return default(T);
            }

            var value = Convert.ChangeType(
                ConfigurationManager.AppSettings[name].ToString(CultureInfo.InvariantCulture), typeof(T));
            if (value.GetType() == typeof(T))
            {
                return (T)value;
            }

            return default(T);
        }

        /// <summary>
        ///     Gets the app setting.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="defaultValue">The default value.</param>
        /// <returns>System.String.</returns>
        public static string GetAppSetting(string name, string defaultValue = null)
        {
            return GetAppSetting<string>(name, defaultValue);
        }

        /// <summary>
        ///     Gets the app setting.
        /// </summary>
        /// <typeparam name="T"> </typeparam>
        /// <param name="name"> The name. </param>
        /// <param name="defaultValue"> The default value. </param>
        /// <returns> </returns>
        public static T GetAppSetting<T>(string name, T defaultValue)
        {
            if (ConfigurationManager.AppSettings[name] == null)
            {
                return defaultValue;
            }

            var value = Convert.ChangeType(
                ConfigurationManager.AppSettings[name].ToString(CultureInfo.InvariantCulture), typeof(T));
            if (value.GetType() == typeof(T))
            {
                return (T)value;
            }

            return defaultValue;
        }
    }
}